package com.zjitc.controller;

import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.zjitc.CountDown.CountDown;
import com.zjitc.common.ServerResponse;
import com.zjitc.model.Cat;
import com.zjitc.model.User;
import com.zjitc.service.CatService;
import com.zjitc.service.UserService;
import com.zjitc.utils.MailUtils;
import java.io.UnsupportedEncodingException;
import java.lang.ProcessBuilder.Redirect;
import java.security.cert.TrustAnchor;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.mail.Session;
import javax.management.relation.Role;
import javax.servlet.http.HttpSession;
import javax.swing.text.View;
import org.apache.ibatis.annotations.ResultMap;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/17 15:43
 * @description:
 */
@Controller
@RequestMapping("/user")
public class UserController {

  @Autowired
  private UserService userService;
  @Autowired
  private CatService catService;

  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public String login(@RequestParam(name = "form-username") String username,
      @RequestParam(name = "form-password") String password, Model model, HttpSession session) {
    String msg = null;
    int cout = userService.checkUsernameCount(username);
    if (cout != 1) {
      msg = "用户不存在，请注册或修改用户名";
      model.addAttribute("msg", msg);
      return "form-2/login";
    }
    User user = null;
    try {
      user = userService.login(username, password);
      if (user.getRole()!=1){
        msg  = "用户尚未激活，请激活后再来";
        model.addAttribute("msg", msg);
        return "user/form-2/login";
      }
    } catch (Exception e) {
      msg = "密码错误，请重新输入";
      model.addAttribute("msg", msg);
      return "user/form-2/login";
    }
    msg = "登录成功，请点击确定跳转到首页";
    session.setAttribute("user", user);
    session.getAttribute("user");
    model.addAttribute("msg", msg);

    /*User response = userService.login(username, password);
    if (response.success()) {
      session.setAttribute("User", response.getData());
      return "redirect:index.jsp";
    }*/
    return "user/form-2/msg02";

  }

  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public String register(@RequestParam("username") String username,
      @RequestParam("password") String password, @RequestParam("email") String email,
      @RequestParam("phone") String phone, @RequestParam("question") String question,
      @RequestParam("answer") String answer, Model model,HttpSession session) {
    String msg = null;
    int count = userService.checkUsernameCount(username);
    if (count == 1) {
      msg = "用户名已被占用，请重新注册";
      model.addAttribute("msg", msg);
      return "user/form-2/register";
    }

    User user = new User();

    user.setCreate_time(new Date());
    user.setUpdate_time(new Date());
    user.setRole(0);
    userService.insertUser(username, password, email, phone, question,
        answer, user.getCreate_time(),
        user.getUpdate_time(), user.getRole());
    /*User user1 = userService.login(username,password);*/
    msg = "用户已注册成功，请前往邮箱等待注册激活验证";
    String code = UUID.randomUUID().toString().replace("-", "");
    //String code = CommonUtils.getUUID()+CommonUtils.getUUID();
    User user1 = userService.findAll(username);
    user.setUuid(code);
    //发送一个邮件
    try {
      MailUtils.sendMail(user1.getEmail(),code,user1.getUsername());

    } catch (Exception e) {
      msg ="邮寄发送失败";
      model.addAttribute("msg",msg);
      e.printStackTrace();
    }
    session.setAttribute("username",username);
    session.setAttribute("emailAddress",user1.getEmail());
    model.addAttribute("user", user);
    model.addAttribute("msg", msg);

//    String returnView="login/form-2/login";
    return "user/form-2/login";
  }

  @RequestMapping(value = "/msg")
  public String msg(String uuid,String username){
    User user = userService.findAll(username);
    if (user.getUuid()==uuid){
      userService.changeRole(username);
      return "user/login";
    }
    return "index";

  }

  @RequestMapping(value = "/cartLIst")
  public String cartLIst(String username, HttpSession session) {
    System.out.println(username);
    String msg = null;
    User user = (User) session.getAttribute("user");
    if (user == null) {
      msg = "请先登录";
      session.setAttribute("msg", msg);
      return "user/form-2/login";
    }
    try {
      //获取cart表
      List list = userService.cartLIst(user.getUsername());
      //将cart表内数据提取 寻找对应的catid
      List catlist = catService.showByUsername(user.getUsername());
      int price = catService.price(user.getUsername());
      int count = catService.num(user.getUsername());
      User user1 = userService.findAll(user.getUsername());
      String adr = user1.getAdress();
      session.setAttribute("address",adr);
      session.setAttribute("cartList", list);
      session.setAttribute("catlist",catlist);
      session.setAttribute("count",count);
      session.setAttribute("allprice",price);
    }catch (Exception e){
      return "cart/checkoutnull";
    }

    return "cart/checkout";
  }

  @RequestMapping(value = "/addCart")
  public String addCart(@RequestParam("catid") Integer catid, HttpSession session, Model model)
      throws UnsupportedEncodingException, InterruptedException {
    String msg = null;
    User user = new User();
    Cat cat = catService.findByCatId(catid);
    String catSpecies = cat.getCatSpecies();
    if ((user = (User) session.getAttribute("user")) == null) {
      msg = "请先登录";
      model.addAttribute("msg", msg);
      return "user/form-2/login";
    }
    int sell;
    sell = catService.chcekSellByCatid(catid);
    if ((sell = catService.chcekSellByCatid(catid)) != 0) {
      msg = "该猫咪已被他人选购，请选择其他猫咪";
      model.addAttribute("msg", msg);
      return "redirect:/cat/CatSpecies.do?CatSpecies=" + catSpecies;
    }
    String uuid = UUID.randomUUID().toString().replace("-", "");
    userService.addCart(catid, user.getUsername(), uuid);
    int num = -1;
    catService.changeCatSell(num, catid);
    catService.changeHost(catid, user.getUsername());
    //若该订单一天内未支付 将售卖状态改为0（可售）代码问题无法从utils访问service层 显示为空指向
    /*CountDown countDown = new CountDown(10,catid);*/
    catSpecies = java.net.URLEncoder.encode(catSpecies, "UTF-8");
    //System.out.println(url);
    return "redirect:/cat/CatSpecies.do?CatSpecies=" + catSpecies;
  }

  @RequestMapping(value = "/remove")
  public void remove(@RequestParam("num") int num, @RequestParam("catid") Integer catid,HttpSession session) {
    catService.changeCatSell(num, catid);
    User user = (User) session.getAttribute("user");
    int price = catService.price(user.getUsername());
    session.setAttribute("allprice",price);
  }


}
